﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Cryptography.X509Certificates;

using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;

namespace ManageSystemServer.Service
{
    public class JwtTokenGenerator
    {
        private readonly JwtSecurityTokenHandler handler;
        private readonly SigningCredentials signing;
        private readonly IConfigurationSection section;
        public JwtTokenGenerator(IConfiguration config)
        {
            handler = new();
            section = config.GetSection("Authentication");
            var cert = new X509Certificate2(section.GetValue<string>("Certificate"));
            signing = new(new X509SecurityKey(cert), SecurityAlgorithms.RsaSha256Signature);
        }

        private SecurityTokenDescriptor CreateDefaultDescriptor() => new()
        {
            Issuer = section.GetValue<string>("Issuer"),
            IssuedAt = DateTime.Now,
            NotBefore = DateTime.Now,
            Expires = DateTime.Now.AddHours(section.GetValue<double>("ValidHours")),
            SigningCredentials = signing
        };

        public string GetToken()
        {
            var descripter = CreateDefaultDescriptor();
            return handler.WriteToken(handler.CreateToken(descripter));
        }

        public string GetToken(IDictionary<string, object> claims)
        {
            var descripter = CreateDefaultDescriptor();
            descripter.Claims = claims;
            return handler.WriteToken(handler.CreateToken(descripter));
        }
    }
}
